/**
 * Copyright (c) 2019 Coder_League(码农联盟)
 * All rights reserved.
 *
 * File：MerchantsService.java
 * History:
 *         2019年5月24日: Initially created, Liangj.
 */
package club.coderleague.ilsp.service.merchants;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import club.coderleague.data.jpa.domain.Page;
import club.coderleague.ilsp.common.config.properties.FileUploadSettings;
import club.coderleague.ilsp.common.domain.beans.AttachBean;
import club.coderleague.ilsp.common.domain.beans.MerchantRemind;
import club.coderleague.ilsp.common.domain.beans.MerchantSettlesExtension;
import club.coderleague.ilsp.common.domain.beans.MerchantsPageBean;
import club.coderleague.ilsp.common.domain.beans.MerchantsSearchName;
import club.coderleague.ilsp.common.domain.beans.MerchantsSearchPhone;
import club.coderleague.ilsp.common.domain.beans.ResultMsg;
import club.coderleague.ilsp.common.domain.enums.EntityState;
import club.coderleague.ilsp.common.util.CommonUtil;
import club.coderleague.ilsp.dao.BanksDao;
import club.coderleague.ilsp.dao.GoodSalesDao;
import club.coderleague.ilsp.dao.MerchantSettlesDao;
import club.coderleague.ilsp.dao.MerchantsDao;
import club.coderleague.ilsp.entities.Banks;
import club.coderleague.ilsp.entities.Goodsales;
import club.coderleague.ilsp.entities.Merchants;
import club.coderleague.ilsp.entities.Merchantsettles;
import club.coderleague.security.AlgorithmBeanFactory;
import club.coderleague.security.algorithm.MD5Signer;

/**
 * 商户
 * @author Liangjing
 */
@Service
public class MerchantsService {

	@Autowired
	MerchantsDao merchantsDao;
	@Autowired 
	FileUploadSettings upload;
	@Autowired
	MerchantSettlesDao merchantSettlesDao;
	@Autowired
	BanksDao banksDao;
	@Autowired
	GoodSalesDao goodSalesDao;
	
	/**
	 * 获取所有的商户数据
	 * @author Liangjing 2019年5月24日
	 * @param pageIndex
	 * @param pageSize
	 * @param key
	 * @param istate
	 * @return
	 */
	public Page<MerchantsPageBean> getTheAllMerchants(String pageIndex,String pageSize,Long searchnameentityid,String searchphonehash,boolean isrecycle) {
		return merchantsDao.getTheAllMerchants(Integer.valueOf(pageIndex), Integer.valueOf(pageSize), searchnameentityid, searchphonehash, isrecycle);
	}
	
	/**
	 * 获取商户编辑页面加载数据
	 * @author Liangjing 2019年5月24日
	 * @param entityid
	 * @return
	 */
	public Map<String,Object> getTheMerchantsEditPagedata(Long entityid) {
		Map<String, Object> map = new HashMap<String, Object>();
		Merchants merchants = merchantsDao.findByEntityid(entityid);
		Map<String, Object> mapattch = this.getTheMerchantsAttach(entityid);
		List<Merchantsettles> list = merchantSettlesDao.findByMerchantidAndEntitystate(entityid, EntityState.VALID.getValue());
		map.put("formdata", merchants);
		map.put("settlelist", list);
		map.put("files", mapattch);
		if(!CommonUtil.isEmpty(merchants.getBankid())) {
			map.put("parentbankid", banksDao.getOne(merchants.getBankid()).getParentbank());
		}else {
			map.put("parentbankid", null);
		}
		return map;
	}
	
	/**
	 * 获取商户查看详情页面加载数据
	 * @author Liangjing 2019年6月8日
	 * @param entityid
	 * @return
	 */
	public Map<String,Object> getTheMerchantsLookInfoPagedata(Long entityid) {
		Map<String, Object> map = new HashMap<String, Object>();
		Merchants merchants = merchantsDao.findByEntityid(entityid);
		Map<String,Object> bank = merchantsDao.getTheBankNameAndParentName(entityid);
		Map<String, Object> mapattch = this.getTheMerchantsAttach(entityid);
		List<Map<String,Object>> list = merchantSettlesDao.getTheLookInfoLoadData(entityid);
		map.put("formdata", merchants);
		map.put("bank", bank);
		map.put("settlelist", list);
		map.put("files", mapattch);
		return map;
	}
	
	/**
	 * 获取商户附件
	 * @author Liangjing 2019年5月24日
	 * @param entityid
	 * @return
	 */
	public Map<String,Object> getTheMerchantsAttach(Long entityid){
		Map<String,Object> map = new HashMap<String, Object>();
		Merchants merchants = merchantsDao.findByEntityid(entityid);
		map.put("idpositive", this.getFileList(upload.getMerchantsPath() + merchants.getIdpositive()));
		map.put("idnegative", this.getFileList(upload.getMerchantsPath() + merchants.getIdnegative()));
		map.put("bankcard", this.getFileList(upload.getMerchantsPath() + merchants.getBankcard()));
		map.put("businesslicense", this.getFileList(upload.getMerchantsPath() + merchants.getBusinesslicense()));
		return map;
	}
	
	private List<AttachBean> getFileList(String path){
		List<AttachBean> list = new ArrayList<AttachBean>();
		AttachBean attachBean = new AttachBean("1", path.substring(path.lastIndexOf("/") + 1,path.length()), path);
		list.add(attachBean);
		return list;
	}
	
	/**
	 * 更新商户对象
	 * @author Liangjing 2019年5月24日
	 * @param merchants
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public ResultMsg updateTheMerchants(String data,String array,String bank) throws Exception {
		Merchants merchants = CommonUtil.jsonToObj(data, Merchants.class);
		Merchants merchantsValidate = merchantsDao.findByMerchantnameAndEntityState(merchants.getMerchantname(), Arrays.asList(new Integer[]{EntityState.VALID.getValue(),EntityState.FROZEN.getValue()}));
		
		//验证入驻信息
		List<MerchantSettlesExtension> list = CommonUtil.jsonToList(array, MerchantSettlesExtension.class);
		for (MerchantSettlesExtension merchantSettlesExtension : list) {
			if(merchantsDao.getIsHaveTheSettleStall(merchantSettlesExtension.getMarketid(), merchantSettlesExtension.getSettlestall(), merchantSettlesExtension.getEntityid())) {
				return new ResultMsg(false, "入驻的'"+merchantSettlesExtension.getMarketname()+"'中'"+merchantSettlesExtension.getSettlestall()+"'摊位已经存在!");
			}
		}
		
		//添加银行信息
		Long bankid = null;
		Map<String,Object> map = CommonUtil.jsonToObj(bank, Map.class);
		if(CommonUtil.isEmpty(merchants.getBankid())) {
			Banks bankparent = banksDao.findByParentbankAndBanknameAndEntitystate(null, map.get("parentname").toString(), EntityState.VALID.getValue());
			if(bankparent != null) {
				Banks bankson = banksDao.findByParentbankAndBanknameAndEntitystate(bankparent.getEntityid(), map.get("sonname").toString(), EntityState.VALID.getValue());
				if(bankson != null) {
					bankid = bankson.getEntityid();
				}else {
					bankson = new Banks(EntityState.VALID.getValue(), bankparent.getEntityid(), map.get("sonname").toString());
					banksDao.save(bankson);
					bankid = bankson.getEntityid();
				}
			}else {
				bankparent = new Banks(EntityState.VALID.getValue(), null, map.get("parentname").toString());
				banksDao.save(bankparent);
				Banks bankson = new Banks(EntityState.VALID.getValue(), bankparent.getEntityid(), map.get("sonname").toString());
				banksDao.save(bankson);
				bankid = bankson.getEntityid();
			}
		}else {
			bankid = merchants.getBankid();
		}
		
		Long merchantid = null;
		if(CommonUtil.isEmpty(merchants.getEntityid())) {
			if(merchantsValidate != null) {
				return new ResultMsg(false, "商户名已存在!");
			}
			Merchants merchantsNew = new Merchants(EntityState.VALID.getValue(), merchants.getMerchantname(), merchants.getMerchantphone(), AlgorithmBeanFactory.getAlgorithmBean(MD5Signer.class).sign(merchants.getMerchantphone()), null, merchants.getIdnumber(), bankid, merchants.getAccountname(), merchants.getBcnumber(), merchants.getIdpositive(), merchants.getIdnegative(), merchants.getBankcard(), merchants.getBusinesslicense(), true, true, 0.0, 0.0, null);
			merchantsDao.save(merchantsNew);
			merchantid = merchantsNew.getEntityid();
		}else {
			merchantid = merchants.getEntityid();
			if(merchantsValidate != null) {
				if(merchantsValidate.getEntityid() != merchants.getEntityid()) {
					return new ResultMsg(false, "商户名已存在!");
				}else {
					merchantsValidate.setAccountname(merchants.getAccountname());
					merchantsValidate.setBankid(bankid);
					merchantsValidate.setMerchantname(merchants.getMerchantname());
					merchantsValidate.setMerchantphone(merchants.getMerchantphone());
					merchantsValidate.setPhonehash(AlgorithmBeanFactory.getAlgorithmBean(MD5Signer.class).sign(merchants.getMerchantphone()));
					merchantsValidate.setIdnumber(merchants.getIdnumber());
					merchantsValidate.setBcnumber(merchants.getBcnumber());
					if(merchants.getIdpositive() != null) {
						merchantsValidate.setIdpositive(merchants.getIdpositive());
					}
					if(merchants.getIdnegative() != null) {
						merchantsValidate.setIdnegative(merchants.getIdnegative());
					}
					if(merchants.getBankcard() != null) {
						merchantsValidate.setBankcard(merchants.getBankcard());
					}
					if(merchants.getBusinesslicense() != null) {
						merchantsValidate.setBusinesslicense(merchants.getBusinesslicense());
					}
				}
			}else {
				Merchants merchantsEdit = merchantsDao.findByEntityid(merchants.getEntityid());
				merchantsEdit.setAccountname(merchants.getAccountname());
				merchantsEdit.setBankid(bankid);
				merchantsEdit.setMerchantname(merchants.getMerchantname());
				merchantsEdit.setMerchantphone(merchants.getMerchantphone());
				merchantsEdit.setPhonehash(AlgorithmBeanFactory.getAlgorithmBean(MD5Signer.class).sign(merchants.getMerchantphone()));
				merchantsEdit.setIdnumber(merchants.getIdnumber());
				merchantsEdit.setBcnumber(merchants.getBcnumber());
				if(merchants.getIdpositive() != null) {
					merchantsEdit.setIdpositive(merchants.getIdpositive());
				}
				if(merchants.getIdnegative() != null) {
					merchantsEdit.setIdnegative(merchants.getIdnegative());
				}
				if(merchants.getBankcard() != null) {
					merchantsEdit.setBankcard(merchants.getBankcard());
				}
				if(merchants.getBusinesslicense() != null) {
					merchantsEdit.setBusinesslicense(merchants.getBusinesslicense());
				}
			}
		}
		//更新入驻信息
		List<Merchantsettles> listMerchantSettles = merchantSettlesDao.findByMerchantid(merchantid);
		if(!CommonUtil.isEmpty(listMerchantSettles)) {
			for (Merchantsettles merchantsettles : listMerchantSettles) {
				if(merchantsettles.getEntitystate() == EntityState.INVALID.getValue()) {
					continue;
				}
				boolean isdel = true;
				for (MerchantSettlesExtension merchantSettlesExtension : list) {
					if(merchantsettles.getMarketid().equals(merchantSettlesExtension.getMarketid()) && merchantsettles.getSettlestall().equals(merchantSettlesExtension.getSettlestall())) {
						isdel = false;
						break;
					}
				}
				if(isdel) {
					this.updateTheGoodSalesRefState(merchantsettles.getEntityid(), EntityState.INVALID.getValue());
					merchantsettles.setEntitystate(EntityState.INVALID.getValue());
				}
			}
			for (MerchantSettlesExtension merchantSettlesExtension : list) {
				boolean isadd = true;
				for (Merchantsettles merchantsettles : listMerchantSettles) {
					if(merchantsettles.getMarketid().equals(merchantSettlesExtension.getMarketid()) && merchantsettles.getSettlestall().equals(merchantSettlesExtension.getSettlestall())) {
						if(merchantsettles.getEntitystate() != EntityState.VALID.getValue()) {
							this.updateTheGoodSalesRefState(merchantsettles.getEntityid(), EntityState.VALID.getValue());
							merchantsettles.setEntitystate(EntityState.VALID.getValue());
						}
						isadd = false;
						break;
					}
				}
				if(isadd) {
					Merchantsettles merchantsettles = new Merchantsettles(EntityState.VALID.getValue(), merchantSettlesExtension.getMarketid(), merchantid, merchantsDao.getTheMaxAddOneSettleSerials(merchantSettlesExtension.getMarketid()), merchantSettlesExtension.getSettlestall());
					merchantSettlesDao.save(merchantsettles);
				}
			}
		}else {
			for (MerchantSettlesExtension merchantSettlesExtension : list) {
				Merchantsettles merchantsettles = new Merchantsettles(EntityState.VALID.getValue(), merchantSettlesExtension.getMarketid(), merchantid, merchantsDao.getTheMaxAddOneSettleSerials(merchantSettlesExtension.getMarketid()), merchantSettlesExtension.getSettlestall());
				merchantSettlesDao.save(merchantsettles);
			}
			
		}
		
		return new ResultMsg(true, "操作成功!");
	}
	
	/**
	 * 更新商户状态
	 * @author Liangjing 2019年5月24日
	 * @param entityids
	 * @param istate
	 * @return
	 */
	public ResultMsg updateTheMerchantsState(String entityids,Integer istate) {
		if(!CommonUtil.isEmpty(entityids)) {
			if(istate == EntityState.VALID.getValue()) {
				for (Long entityid : CommonUtil.toLongArrays(entityids)) {
					Merchants merchants = merchantsDao.findByEntityid(entityid);
					Merchants merchantsValidate = merchantsDao.findByMerchantnameAndEntityState(merchants.getMerchantname(), Arrays.asList(new Integer[]{EntityState.VALID.getValue(),EntityState.FROZEN.getValue()}));
					if(merchantsValidate != null) {
						return new ResultMsg(false, "恢复数据中存在重复!");
					}
				}
			}
			for (Long entityid : CommonUtil.toLongArrays(entityids)) {
				this.updateTheRefState(entityid, istate);
				Merchants merchants = merchantsDao.findByEntityid(entityid);
				merchants.setEntitystate(istate);
			}
		}
		return new ResultMsg(true, "操作成功!");
	}
	
	/**
	 * 更新商户入驻和商品销售关联的数据状态
	 * @author Liangjing 2019年7月30日
	 * @param merchantid
	 * @param istate
	 */
	public void updateTheRefState(Long merchantid, Integer istate) {
		if(istate == EntityState.INVALID.getValue() || istate == EntityState.FROZEN.getValue()) {
			List<Merchantsettles> list = merchantSettlesDao.findByMerchantidAndEntitystate(merchantid, EntityState.VALID.getValue());
			for (Merchantsettles merchantsettles : list) {
				List<Goodsales> listGood = goodSalesDao.findBySettleidAndEntitystateIn(merchantsettles.getEntityid(), Arrays.asList(new Integer[] {EntityState.VALID.getValue(), EntityState.PUBLISHED.getValue()}));
				for (Goodsales goodsales : listGood) {
					goodsales.setOriginalstate(goodsales.getEntitystate());
					goodsales.setEntitystate(EntityState.CASCADEDELETED.getValue());
				}
				merchantsettles.setEntitystate(EntityState.CASCADEDELETED.getValue());
			}
		}else if(istate == EntityState.VALID.getValue()) {
			List<Merchantsettles> list = merchantSettlesDao.findByMerchantidAndEntitystate(merchantid, EntityState.CASCADEDELETED.getValue());
			for (Merchantsettles merchantsettles : list) {
				List<Goodsales> listGood = goodSalesDao.findBySettleidAndEntitystateIn(merchantsettles.getEntityid(), Arrays.asList(new Integer[] {EntityState.CASCADEDELETED.getValue()}));
				for (Goodsales goodsales : listGood) {
					goodsales.setEntitystate(goodsales.getOriginalstate());
				}
				merchantsettles.setEntitystate(EntityState.VALID.getValue());
			}
		}
	}
	
	/**
	 * 更新商品销售关联的数据状态
	 * @author Liangjing 2019年7月30日
	 * @param merchantsettles
	 * @param istate
	 */
	public void updateTheGoodSalesRefState(Long merchantsettlesid, Integer istate) {
		if(istate == EntityState.INVALID.getValue()) {
			List<Goodsales> listGood = goodSalesDao.findBySettleidAndEntitystateIn(merchantsettlesid, Arrays.asList(new Integer[] {EntityState.VALID.getValue(), EntityState.PUBLISHED.getValue()}));
			for (Goodsales goodsales : listGood) {
				goodsales.setOriginalstate(goodsales.getEntitystate());
				goodsales.setEntitystate(EntityState.CASCADEDELETED.getValue());
			}
		}else if(istate == EntityState.VALID.getValue()) {
			List<Goodsales> listGood = goodSalesDao.findBySettleidAndEntitystateIn(merchantsettlesid, Arrays.asList(new Integer[] {EntityState.CASCADEDELETED.getValue()}));
			for (Goodsales goodsales : listGood) {
				goodsales.setEntitystate(goodsales.getOriginalstate());
			}
		}
	}
	
	/**
	 * 获取所有有效的市场
	 * @author Liangjing 2019年6月8日
	 * @return
	 */
	public List<Map<String,Object>> getTheAllMarkets() {
		Map<String,Object> map = new HashMap<String, Object>();
		List<Map<String,Object>> list = merchantsDao.getTheAllMarkets();
		map.put("id", "-1");
		map.put("name", "请选择");
		list.add(0, map);
		return list;
	}
	/**
	 * 获取对应展开查询商户列表
	 * @author Liangjing 2019年7月25日
	 * @return
	 */
	public List<MerchantsSearchName> getTheAllSearchMerchant() {
		List<MerchantsSearchName> list =merchantsDao.getTheAllSearchMerchant();
		MerchantsSearchName searchName = new MerchantsSearchName(Long.valueOf("-1"), "请选择");
		list.add(0, searchName);
		return list;
	}
	
	/**
	 * 获取对应展开查询商户电话
	 * @author Liangjing 2019年7月25日
	 * @return
	 */
	public List<Map<String,Object>> getTheAllSearchMerchantPhoneHash() {
		List<Map<String,Object>> listreturn = new ArrayList<Map<String,Object>>();
		List<MerchantsSearchPhone> list = merchantsDao.getTheAllSearchMerchantPhoneHash();
		for (MerchantsSearchPhone merchantsSearchPhone : list) {
			boolean isadd = true;
			for (Map<String,Object> map : listreturn) {
				if(map.get("phonehash").equals(merchantsSearchPhone.getPhonehash())) {
					isadd = false;
					break;
				}
			}
			if(isadd) {
				Map<String,Object> map = new HashMap<String, Object>();
				map.put("phonehash", merchantsSearchPhone.getPhonehash());
				map.put("merchantphone", merchantsSearchPhone.getMerchantphone());
				listreturn.add(map);
			}
		}
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("phonehash", "-1");
		map.put("merchantphone", "请选择");
		listreturn.add(0, map);
		return listreturn;
	}
	
	/**
	 * 获取所有开户行父级银行
	 * @author Liangjing 2019年7月26日
	 * @return
	 */
	public List<Map<String,Object>> getTheAllParentBanks() {
		return merchantsDao.getTheAllParentBanks();
	}
	
	/**
	 * 获取所有开户行子级银行
	 * @author Liangjing 2019年7月26日
	 * @param entityid
	 * @return
	 */
	public List<Map<String,Object>> getTheAllSonBanks(Long entityid) {
		return merchantsDao.getTheAllSonBanks(entityid);
	}
	
	/**
	 * 查询商户提醒。
	 * @author Chrise 2019年8月22日
	 * @param merchant 商户标识。
	 * @return 商户提醒对象。
	 */
	public MerchantRemind queryMerchantRemind(long merchant) {
		return merchantsDao.queryMerchantRemind(merchant);
	}
}
